package com.zeus.web.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取ip 地址
 */
public class IPAddrUtils {
    private final static String REQUEST_KEY = "unknown";

    /**
     * 获取客户端请求的真实ip
     * 过滤反向代理的ip 多级反向代理的话，X-Forwarded-For的值并不止一个
     * 如：X-Forwarded-For：192.168.1.110， 192.168.1.120， 192.168.1.130， 192.168.1.100
     * 用户真实IP为： 192.168.1.110
     */
    public static String getIpAddress(HttpServletRequest request) {
        String remotIp = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(remotIp) || REQUEST_KEY.equalsIgnoreCase(remotIp)) {
            remotIp = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(remotIp) || REQUEST_KEY.equalsIgnoreCase(remotIp)) {
            remotIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(remotIp) || REQUEST_KEY.equalsIgnoreCase(remotIp)) {
            remotIp = request.getRemoteAddr();
        }
        //如果是多级代理，取第一个IP为客户ip
        if (StringUtils.isNotBlank(remotIp) && StringUtils.indexOf(remotIp, ",") > 0) {
            String[] ipArr = StringUtils.split(remotIp, ",");
            remotIp = ipArr[0];
        }
        return remotIp;
    }
}
